package cn.kgc.vue.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.service.UserService;
import cn.kgc.vue.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;

/**
* @author mengshun
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-10-31 08:44:32
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public Map register(User user) {

        HashMap<String, Object> result = new HashMap<>();
        //  1. 判定用户名是否存在
        String username = user.getUsername();
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,username);

        User usr = userMapper.selectOne(lambda);
        if (ObjectUtils.isNotNull(usr)){

            result.put("code",110);
            result.put("msg","用户名被占用");
            return result;
        }


        // 2.添加用户信息到数据
        String s = SecureUtil.md5(user.getPassword());
        user.setPassword(s);

        userMapper.insert(user);

        result.put("code",0);
        result.put("msg","注册成功");

        return result;
    }

    @Override
    public Map login(User user) {

        HashMap<String, Object> result = new HashMap<>();

        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,user.getUsername())
                .eq(User::getPassword, SecureUtil.md5(user.getPassword()));

        User usr = userMapper.selectOne(lambda);

        if (ObjectUtils.isNull(usr)){
            result.put("code",111);
            result.put("msg","用户名或密码错误");
            return  result;
        }

        result.put("code",0);
        result.put("msg","登录成功");

        return result;
    }
}




